import { AppComstants } from '@/common/comstants.js';
import { appLocalStorage } from '@/utils/storage-util.js';
import { createRouter, createWebHashHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { initRoutes } from '@/utils/router-update-util';
import routes from './base-route.js';
import { useTabStore } from '@/store/tab-store';
import { useUserStore } from '@/store/user-store';

NProgress.configure({ showSpinner: false });

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
});

initRoutes(router);

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  // 获取用户令牌
  const token = appLocalStorage.getItem(AppComstants.Token);

  if (token) {
    // 每次都获取用户信息
    await useUserStore().updateUserInfo();
    useTabStore().addTab(to);
    next();
  } else if (!to.meta.isAuth) {
    next();
  } else {
    next('/login');
  }
});

router.afterEach((to, from) => {
  NProgress.done();
});

export default router;
